package com.findviewbydream.evil.eda.Login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.IntentData;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.MainActivity;
import com.findviewbydream.evil.eda.R;
import com.findviewbydream.evil.eda.Utils.Dialog.CustomMaterialDialog;
import com.findviewbydream.evil.eda.Utils.NetUtils;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.flyco.dialog.listener.OnBtnClickL;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Login
 * 时间：16-9-27 下午4:13
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：
 ********************************************/
public class Login extends AppCompatActivity
{
    private static boolean isDebug = Utils.getDubug();
    private static int COUNTDOWN = 60;/*发送短信的倒计时*/

    private ImageView background;
    private CardView bottom;
    private TextInputEditText phone_InputEditText;
    private TextInputLayout phone_InputLayout;
    private TextInputEditText code_InputEditText;
    private TextInputLayout code_InputLayout;
    private LinearLayout editText_layout;
    private CardView top;
    private Button submit;

    private boolean isCoedSuccess = false;/*判断是否完成了短信验证*/
    private Button code_button;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_new);
        SMSSDK.initSDK(this, Data.SMSSDK_APP_KEY, Data.SMSSDK_APP_SECRET);
        initView();
        Utils.Glide(R.drawable.login_background, background);
        setAnimation();
        setEditText_layout();
        setCode();/*设置短信发送按钮*/
        setSubmit();/*设置登陆按钮*/
        setSMSS();
    }

    /**
     * 初始化控件
     */
    private void initView()
    {
        background = (ImageView) findViewById(R.id.background);
        bottom = (CardView) findViewById(R.id.bottom);
        phone_InputEditText = (TextInputEditText) findViewById(R.id.phone_InputEditText);
        phone_InputLayout = (TextInputLayout) findViewById(R.id.phone_InputLayout);
        code_InputEditText = (TextInputEditText) findViewById(R.id.code_InputEditText);
        code_InputLayout = (TextInputLayout) findViewById(R.id.code_InputLayout);
        editText_layout = (LinearLayout) findViewById(R.id.editText_layout);
        top = (CardView) findViewById(R.id.top);
        submit = (Button) findViewById(R.id.submit);
        code_button = (Button) findViewById(R.id.code_button);
    }

    /**
     * 设置动画
     */
    private void setAnimation()
    {
        AnimationSet top_set = new AnimationSet(true);
        Animation top_t = new TranslateAnimation(0, 0, -500, 0);
        top_t.setDuration(2500);
        Animation a = new AlphaAnimation(0, 1);
        a.setDuration(2300);

        top_set.addAnimation(top_t);
        top_set.addAnimation(a);
        top.setAnimation(top_set);
        top_set.startNow();

        AnimationSet bottom_set = new AnimationSet(true);
        Animation bottom_t = new TranslateAnimation(0, 0, 500, 0);
        bottom_t.setDuration(2500);

        bottom_set.addAnimation(bottom_t);
        bottom_set.addAnimation(a);
        bottom.setAnimation(bottom_set);
        bottom_set.startNow();

        Animation anim_a = new AlphaAnimation(0, 1);
        anim_a.setDuration(3500);
        anim_a.setFillEnabled(true);
        editText_layout.setAnimation(anim_a);
        submit.setAnimation(anim_a);
        anim_a.startNow();
    }

    /**
     * 设置输入动作
     */
    private void setEditText_layout()
    {
        phone_InputEditText.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
                phone_InputLayout.setErrorEnabled(false);
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {

            }

            @Override
            public void afterTextChanged(Editable editable)
            {
                if (phone_InputEditText.getText().toString().trim().length() != 11)
                {
                    phone_InputLayout.setErrorEnabled(true);
                    phone_InputLayout.setError("请输入正确的手机号");
                }
            }
        });
    }

    /**
     * 设置提交选项
     */
    private void setCode()
    {
        code_InputEditText.setOnClickListener(view -> code_InputLayout.setErrorEnabled(false));
        code_button.setOnClickListener(view -> {
            /*未完成短信验证*/
            if (!isCoedSuccess)
                if (phone_InputEditText.getText().toString().trim().length() == 11)
                    sendCode();
        });
    }

    /**
     * 发送短信验证码
     */
    private void sendCode()
    {
        SMSSDK.getVerificationCode("+86", phone_InputEditText.getText().toString().trim());
        Utils.Toast(phone_InputEditText.getText().toString().trim());
        code_button.setClickable(false);
        new Utils.SHandler()
        {
            int i = COUNTDOWN;
            CustomMaterialDialog dialog;

            @Override
            public void thread(Handler handler)
            {
                super.thread(handler);
                while (i > 0)
                {
                    i--;
                    handler.sendEmptyMessage(0);
                    Utils.Threadsleep(1000);
                }
            }

            @Override
            public void handler()
            {
                code_button.setText("再次发送" + i + "s");
                if (i == 0)
                {
                    code_button.setClickable(true);
                    code_button.setText("获取验证码");

                    if (!isCoedSuccess)
                    {
                        dialog = new CustomMaterialDialog(Login.this)
                                .setTitle("发送语音验证码")
                                .setMessage("没有收到短息验证码？是否获取语音验证码？")
                                .setButtonText("取消", "获取")
                                .setButtonOnClick(
                                        () -> dialog.dismiss()
                                        , () -> {
                                            dialog.dismiss();
                                            sendCode();
                                            SMSSDK.getVoiceVerifyCode("+86"
                                                    , phone_InputEditText.getText().toString().trim());
                                        });
                        dialog.show();
                    }
                }
            }
        }.startByCustom();
    }

    /**
     * 设置登陆按钮
     */
    private void setSubmit()
    {
        submit.setOnClickListener(view -> {
            if (isDebug)
            {
                submit.setText("提交中，请稍后……");
                submit.setClickable(false);
                afterSuccess();
            }
            else
            {
                if (phone_InputEditText.getText().toString().trim().length() == 11)
                    if (code_InputEditText.getText().toString().trim().length() != 0)
                    {
                        submit.setText("提交中，请稍后……");
                        submit.setClickable(false);
                        SMSSDK.submitVerificationCode("+86"
                                , phone_InputEditText.getText().toString().trim()
                                , code_InputEditText.getText().toString().trim());
                    }
                    else
                    {
                        code_InputLayout.setErrorEnabled(true);
                        code_InputLayout.setError("请填写验证码");
                    }
                else
                {
                    code_InputLayout.setErrorEnabled(true);
                    phone_InputLayout.setError("请填写正确的手机号");
                }
            }
        });
    }

    /**
     * 短信验证码
     */
    private void setSMSS()
    {
        EventHandler eventHandler = new EventHandler()
        {
            @Override
            public void afterEvent(int event, int result, Object data)
            {
                if (result == SMSSDK.RESULT_COMPLETE)
                {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE)
                    {
                        //提交验证码成功
                        HashMap<String, Object> map = (HashMap<String, Object>) data;
                        Log.i("验证码", map.get("phone").toString());
                        if (map.get("phone").toString().equals(phone_InputEditText.getText().toString().trim()))
                        {
                            Utils.Log("验证成功");
                            afterSuccess();
                        }
                        else
                        {
                            Utils.Log("验证失败");
                            code_InputLayout.setErrorEnabled(true);
                            code_InputLayout.setError("短信验证错误");
                            submit.setText("登陆");
                            submit.setClickable(true);
                        }
                    }
                    else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE)
                    {
                        //获取验证码成功
                    }
                    else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES)
                    {
                        //返回支持发送验证码的国家列表
                    }
                }
                else
                {
                    ((Throwable) data).printStackTrace();
                }
            }
        };

        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
    }

    /**
     * 验证码验证成功后的操作
     */
    private void afterSuccess()
    {
        isCoedSuccess = true;
        if (phone_InputEditText.getText().toString().trim().length() == 11)
        {
            /**
             * 网络加载
             */
            OkHttpUtils.post()
                    .url(Data.IP + "LoginServlet")
                    .addParams("type", "register")
                    .addParams("phone", phone_InputEditText.getText().toString().trim())
                    .addParams("imei", UserData.getUserIMEI())
                    .build()
                    .execute(new StringCallback()
                    {
                        CustomMaterialDialog dialog;

                        @Override
                        public void onError(Call call, Exception e, int id)
                        {
                            e.printStackTrace();
                            NetUtils.reportError(Login.this, e);
                        }

                        @Override
                        public void onResponse(String response, int id)
                        {
                            Utils.Logger(response);
                            /*SUCCESS为老用户，NEW为新用户*/
                            if (response.equals("SUCCESS") || response.equals("NEW"))
                            {
                                startActivity(new Intent(Login.this, IntentData.getMainActivity()));

                                SharedPreferences preferences = getSharedPreferences("user", MODE_PRIVATE);
                                SharedPreferences.Editor editor = preferences.edit();
                                UserData.setUserPhoneNum(phone_InputEditText.getText().toString().trim());
                                editor.putString("up", UserData.getUserPhoneNum());
                                editor.putString("ui", UserData.getUserIMEI());
                                editor.apply();

                                finish();
                            }
                            else if (response.equals("BLACK"))
                            {
                                dialog = new CustomMaterialDialog(Login.this);
                                dialog.setMessage("由于您的违规操作，您已经被列入黑名单中，请规范您的操作行为，等待解封！")
                                        .setCanBack(false)
                                        .setButtonText("退出")
                                        .setButtonOnClick((OnBtnClickL) () -> {
                                            dialog.dismiss();
                                            new Handler().postDelayed(() -> finish(), 500);
                                        }).show();
                                dialog.show();
                            }
                            else if (response.equals("NOT_IN_HANDAN"))
                            {
                                dialog = new CustomMaterialDialog(Login.this)
                                        .setTitle("提示")
                                        .setMessage("您的手机号归属地是不\"邯郸地区\"的说……十分抱歉啦" +
                                                "，我们暂时尚未开展其他地区的服务" +
                                                "，还请您耐心等待它的到来吧！")
                                        .setCanBack(false)
                                        .setButtonText("退出")
                                        .setButtonOnClick(() -> {
                                            dialog.dismiss();
                                            new Handler().postDelayed(() -> finish(), 600);
                                        });
                                dialog.show();
                            }
                            else if (response.equals("ERROR"))
                            {
                                submit.setError("");
                                submit.setText("发生错误，请重试");
                            }
                        }
                    });
        }
    }
}
